#include <lvgl.h>
#include <rtthread.h>
#include "drv_lcd.h"

/**********************************************************************
 *      DEFINES
 **********************************************************************/
#define BUF_SIZE 240 * 24

static void flush_cb(lv_disp_drv_t * drv, const lv_area_t * area, lv_color_t * color)
{
    lcd_show_image(area->x1, area->y1, lv_area_get_width(area), lv_area_get_height(area), (uint8_t*)color);
    lv_disp_flush_ready(drv);
}

void lv_port_disp_init(void)
{
    static lv_color_t *buf1;
    static lv_disp_draw_buf_t draw_buf;
    static lv_disp_drv_t disp_drv;

    buf1 = rt_malloc(BUF_SIZE * sizeof(lv_color_t));
    lv_disp_draw_buf_init(&draw_buf, buf1, NULL, BUF_SIZE);

    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf = &draw_buf;
    disp_drv.hor_res = 240;
    disp_drv.ver_res = 320;
    disp_drv.flush_cb = flush_cb;
    lv_disp_t * disp = lv_disp_drv_register(&disp_drv);
    lv_disp_set_theme(disp, lv_theme_basic_init(disp));
}

/**********************************************************************
 *   STATIC FUNCTIONS
 **********************************************************************/
unsigned int pos[2] = {0};
static void touch_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data)
{
//    static lv_coord_t last_x = 0;
//    static lv_coord_t last_y = 0;
//    bsp_ns2009_getPos(pos);
//    if(pos[0] || pos[1])
//    {
//        last_x = pos[0];
//        last_y = pos[1];
//        data->state = LV_INDEV_STATE_PR;
//    }
//    else
//        data->state = LV_INDEV_STATE_REL;

//    data->point.x = last_x;
//    data->point.y = last_y;

}

static bool touchpad_is_pressed(void)
{
    if(pos[0] || pos[1])
    {
        return true;
    }
    else
    {
        return false;
    }
}

static void touchpad_get_xy(lv_coord_t * x, lv_coord_t * y)
{
    (*x) = pos[0];
    (*y) = pos[1];
}


void lv_port_indev_init(void)
{
    static lv_indev_drv_t indev_drv;
    
    lv_indev_drv_init(&indev_drv);
    indev_drv.read_cb = touch_read_cb;
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    lv_indev_drv_register(&indev_drv);
}

